package per.zhy.demo.apple;

import com.alibaba.fastjson.JSONObject;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhy on 2018/4/13.
 */
public class Captcha {
    String path = "E:\\test\\";
    String before = "E:\\test\\before\\";
    String after = "E:\\test\\after\\";

    static String tesseract = "C:\\Program Files (x86)\\Tesseract-OCR\\tessdata";

    int times = 1;

    public void getCaptcha(AppleCookie appleCookie) throws IOException, TesseractException, InterruptedException {
        String imgBase64 = getImgBase64(appleCookie);//获取验证码
        JSONObject jsonObject = JSONObject.parseObject(imgBase64);//解析
        appleCookie.setCaptcha_id(jsonObject.getIntValue("id"));
        appleCookie.setCaptcha_token(jsonObject.getString("token"));
        String imgStr = jsonObject.getJSONObject("payload").getString("content");
        System.out.println(imgStr);
        String name = saveImage(imgStr);//保存图片
        generatorImg3(name);//验证码二值化
    }

    @Test
    public void getCaptcha() throws IOException, TesseractException, InterruptedException {
        AppleCookie appleCookie = new AppleCookie();
        String[] data = new RegAppleAcct().getInfo();//进入页面
        appleCookie.setAidsp(data[0]);
        appleCookie.setScnt(data[1]);

        for (int i = 0; i < times; i++) {
            String imgBase64 = getImgBase64(appleCookie);//获取验证码
            JSONObject jsonObject = JSONObject.parseObject(imgBase64);//解析
            String imgStr = jsonObject.getJSONObject("payload").getString("content");
            System.out.println(imgStr);

            String name = saveImage(imgStr);//保存图片
            generatorImg3(name);//验证码二值化
            view(name);//识别
            TimeUnit.MILLISECONDS.sleep(500);
        }
    }

    /**
     * 获取图片base64
     *
     * @return
     * @throws IOException
     */
    private String getImgBase64(AppleCookie appleCookie) throws IOException {
        Response capTchaResponse = Request.Post("https://appleid.apple.com/captcha")
                .addHeader("User-Agent", "Mozilla/5.0 [en](Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36")
                .addHeader("X-Apple-ID-Session-Id", appleCookie.getAidsp())
                .addHeader("scnt", appleCookie.getScnt())
                .addHeader("Origin", "https://appleid.apple.com")
                .addHeader("X-Apple-I-FD-Client-Info", "{\"U\":\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36\",\"L\":\"zh-CN\",\"Z\":\"GMT+08:00\",\"V\":\"1.1\",\"F\":\"FOa44j1e3NlY5BSo9z4ofjb75PaK4Vpjt.gEngMQEjZrVglE4Ww.GEFF0Yz3ccbbJYMLgiPFU77qZoOSix5ezdstlYysrhsui6.IQnu3xgycUPm8LKfAaZ4pAJZ7OQuyPBB2SCXw2SCVL6yXyjaY1WMsiZRPrwVL6tqAhbrmQkLNbXky.7bc7.lzXJJIneGffLMC7EZ3QHPBirTYKUowRslzRQqwSM2V8htx1TqUJEhO3f9p_nH1uzjkD6myjaY2_GGEQIgwe98vDdYejftckuyPBDjaY2ftckZZLQ084akJmZxIFVCqv9_jpidPNs0ojpVMZ90L5H6fqUdHz15tTma1kxNGYjpjV2pNk0ug97SIVb40xN4t23f282p9KyP4yQhSFQ_v9NA14WX3NlY5DuY25BNnOVgw24uy.5f8\"}")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36")
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("X-Apple-Request-Context", "create")
                .addHeader("X-DevTools-Emulate-Network-Conditions-Client-Id", "(2E0AB4265CF3C9E9716F6466BAE7ADDA)")
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("X-Apple-Api-Key", "cbf64fd6843ee630b463f358ea0b707b")
                .addHeader("Referer", "https://appleid.apple.com/account")
                .addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Cookie", "idclient=web; dslang=CN-ZH; site=CHN; aidsp=" + appleCookie.getAidsp() + ";")
                .body(new StringEntity("{\"type\":\"IMAGE\"}", "UTF-8"))
                .execute();
        HttpResponse httpResponse = capTchaResponse.returnResponse();
        appleCookie.setScnt(httpResponse.getHeaders("scnt")[0].getValue());
        return EntityUtils.toString(httpResponse.getEntity());
//        return capTchaResponse.returnContent().asString();
    }

    /**
     * 图片二值化
     *
     * @param name
     * @throws IOException
     */
    private void generatorImg3(String name) throws IOException {
        BufferedImage img = ImageIO.read(new File(before + name + ".jpeg"));
        int width = img.getWidth();
        int hight = img.getHeight();

        Color white = new Color(255, 255, 255);
        Color black = new Color(0, 0, 0);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < hight; y++) {
                Color color = new Color(img.getRGB(x, y));
                if (color.getRed() > 36 & color.getBlue() > 16 & color.getGreen() > 16) {
                    img.setRGB(x, y, white.getRGB());
                } else {
                    img.setRGB(x, y, black.getRGB());
                }
            }
        }
        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);

        ColorConvertOp op = new ColorConvertOp(cs, null);
        img = op.filter(img, null);
        ImageIO.write(img, "JPEG", new File(after + name + "_2.jpeg"));
    }


    @Test
    public void view() throws TesseractException {
        File f = new File(after);
        File[] files = f.listFiles();

        Arrays.sort(files);

        ITesseract instance = new Tesseract();  // JNA Interface Mapping
        instance.setDatapath(tesseract);
        instance.setLanguage("eng");
        for (File imageFile : files) {

            String result = instance.doOCR(imageFile);
            System.out.println(imageFile.getName() + "=======" + result);
        }
    }

    /**
     * 识别
     *
     * @param name
     * @throws TesseractException
     */
    private void view(String name) throws TesseractException {
        File imageFile = new File(after + name + "_2.jpeg");
        ITesseract instance = new Tesseract();  // JNA Interface Mapping
        instance.setDatapath(tesseract);
//        instance.setLanguage("my");
        String result = instance.doOCR(imageFile);
        System.out.println(result);
    }

    /**
     * @param imgStr
     * @return
     */
    private String saveImage(String imgStr) {
        if (imgStr == null) {
            throw new RuntimeException("imgStr is null");
        }
        String name = null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(imgStr);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            name = System.currentTimeMillis() + "";
            OutputStream out = new FileOutputStream(before + name + ".jpeg");
            out.write(b);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return name;
    }
}